/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"errors"
	"fmt"
	wxcard "github.com/chanxuehong/wechat/mp/card"
	wxacitveuserform "github.com/chanxuehong/wechat/mp/card/membercard/activateuserform"
	wxcardqr "github.com/chanxuehong/wechat/mp/card/qrcode"
	"github.com/chanxuehong/wechat/mp/card/testwhitelist"
	"github.com/chanxuehong/wechat/mp/core"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/common"
	. "saas_sys_base/modules/merchantCard/models"
	. "saas_sys_base/modules/user/service"
)

type MchMemberCardService struct {
	// add your model here
	tbMchMemberCard MchMemberCard
	wxUserService WxUserService
	mchUserMemberCardService MchUserMemberCardService

}

func (t *MchMemberCardService) ListMchMemberCard(keyword string, page, psize int, orderField, order string) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_mch_member_card", "alias": "t1"},
		"fields": []string{"t1.*"},
		"join":   []map[string]string{
			// map[string]string{"table": "tb_xx as t2", "on": "t2.xid = t1.id"},
		},
		"where": []lego.QMapWhereField{
			{"t1.if_del", "=", 0, "AND", false},
		},
		"search": map[string]string{
			//"t1.id": req.Keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}

	if orderField != "" && order != "" {
		orderStr := fmt.Sprintf("t1.%s %s", orderField, order)
		queryMap["orders"] = []string{orderStr, "t1.cdate asc"}
	}

	return lego.QueryListByMap(queryMap)
}

func (t *MchMemberCardService) ListMchMemberCardByWho(who *common.Who, keyword string, page, psize int, orderField, order string) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_mch_member_card", "alias": "t1"},
		"fields": []string{"t1.*"},
		"join":   []map[string]string{
			//map[string]string{"table": "tb_xxx as t2", "on": "t2.xxx = t1.xxx"},
		},
		"where": []lego.QMapWhereField{
			{"t1.if_del", "=", 0, "AND", false},
			//{"xx.tenant_id", "=", who.TenantId, "AND", false},
			//{"xx.mini_app_id", "=", who.MiniAppId, "AND", false},

		},
		"search": map[string]string{
			//"t1.id": req.Keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}

	if orderField != "" && order != "" {
		orderStr := fmt.Sprintf("t1.%s %s", orderField, order)
		queryMap["orders"] = []string{orderStr, "t1.cdate asc"}
	}
	/*{ //这段生成代码的目的是，当需要根据条件判断，来增加对应where条件时，使用这里的逻辑
		queryWhere := queryMap["where"].([]lego.QMapWhereField)
		if who.TenantId != 0 {
			queryWhere = append(queryWhere, lego.QMapWhereField{"t2.tenant_id", "=", who.TenantId, "AND", false})
		}

		if who.MiniAppId != 0 {
			queryWhere = append(queryWhere, lego.QMapWhereField{"t2.mini_app_id", "=", who.MiniAppId, "AND", false})
		}

	}*/

	return lego.QueryListByMap(queryMap)
}

/* 根据id获取记录
 * -----------------
 */
func (t *MchMemberCardService) GetMchMemberCardById(id int64) *MchMemberCard {
	return t.tbMchMemberCard.RecodeById(id)
}

func (t *MchMemberCardService) GetMchMemberCardByWho(who *common.Who) *MchMemberCard {
	return t.tbMchMemberCard.RecodeByWho(who)
}

/* 添加
 * -----------------
 */
func (t *MchMemberCardService) SaveMchMemberCard(item2add *MchMemberCard) bool {
	return t.tbMchMemberCard.AddRecode(item2add)
}

/* 删除(硬删除)*/
/*func (t *MchMemberCardService) DelMchMemberCardById(id int64) bool {
	return t.tbMchMemberCard.DelRecodeById(id)
}*/

/* 删除(软删除)*/
func (t *MchMemberCardService) SDelMchMemberCardById(id int64) bool {
	return t.tbMchMemberCard.SDelRecodeById(id)
}

/* 更新
 * -----------------*/
func (t *MchMemberCardService) UpdateMchMemberCard(rc *MchMemberCard) bool {
	return t.tbMchMemberCard.UpdateRecode(rc)
}


//appwho wrapper函数
func (t *MchMemberCardService) CreateCardByWho(who *common.Who, card *MchCardUnionMsg) (*MchMemberCard, error) {
	item2add := NewMchMemberCard(who, card)
	isSuccess := t.tbMchMemberCard.AddRecode(item2add)
	if !isSuccess {
		return nil, errors.New("create card failed")
	}
	return item2add, nil
}

func (t *MchMemberCardService) GetCardByWho(appwho *common.Who, MchCardId int64) (*MchMemberCard, error) {
	mchMemberCard := t.tbMchMemberCard.RecodeByIdAndWho(appwho, MchCardId)
	if mchMemberCard == nil {
		return nil, fmt.Errorf("MchCardId<%d> not found", MchCardId)
	}

	return mchMemberCard, nil
}

func (t *MchMemberCardService) SetActivateUserForm(who common.Who, userform *wxacitveuserform.ActiveuserFormPara) (err error) {

	return err
}

func (t *MchMemberCardService) BatchGetByWho(who *common.Who, page, psize int) (result []MchMemberCard, total int64, err error) {
	result, total, err = t.tbMchMemberCard.ListByWho(who, page, psize)
	if err != nil {
		return nil, 0, err
	}

	return result, total, nil
}

func (t *MchMemberCardService) GetMemberCardByWho(who common.Who, MchCardId int64) (mchMemberCard *MchMemberCard, err error) {
	mchMemberCard = t.tbMchMemberCard.RecodeById(MchCardId)
	if mchMemberCard == nil {
		return  nil, fmt.Errorf("MchCardId<%d> not found", MchCardId)
	}

	return mchMemberCard, nil
}

//投放
func (t *MchMemberCardService) CreateQrCodeByWho(appwho common.Who, createReqPara *wxcardqr.CreateQrCodeReqPara) (result *wxcardqr.QrcodeInfo, err error) {

	return result, err
}

//白名单
//投放
func (t *MchMemberCardService) TestWhileListByWho(appwho common.Who, para *testwhitelist.SetParameters) (err error) {

	return err
}

//卡券事件处理函数
func (t *MchMemberCardService) CardPassCheckEventHandler(weappid string, mixedMsg *core.MixedMsg) error {

	return nil
}

func (t *MchMemberCardService) CardNotPassCheckEventHandler(weappid string, mixedMsg *core.MixedMsg) error {

	return nil
}

func (t *MchMemberCardService) CardGetCardEventHandler(weappid string, mixedMsg *core.MixedMsg) (*MchUserMemberCard, error) {
	msg := wxcard.GetUserGetCardEvent(mixedMsg)
	userWho, err := t.GetWhoByWxCardIdAndUnionId(msg.CardId, msg.UnionId)
	if err != nil {
		lego.LogError(fmt.Sprintf("CardGetCardEventHandler fail:<%s>", err.Error()))
		return nil, err
	}

	mchUserMemberCard, err := t.mchUserMemberCardService.CardGetCardEventHandler(userWho, weappid, mixedMsg)
	if err != nil {
		lego.LogError(fmt.Sprintf("CardGetCardEventHandler fail:<%s>", err.Error()))
		return nil, err
	}
	return mchUserMemberCard, err
}

func (t *MchMemberCardService) UserDelCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {

	return nil
}

func (t *MchMemberCardService) UserConsumeCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {

	return nil
}

func (t *MchMemberCardService) UserViewCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	//log.Printf("user_view_card event:\n%s\n", ctx.MsgPlaintext)
	// TODO统计计数以后再考虑

	return nil
	//ctx.NoneResponse()
}

func (t *MchMemberCardService) UserEnterSessionEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	//log.Printf("user_enter_session_from_card event:\n%s\n", ctx.MsgPlaintext)
	// TODO以后再考虑
	return nil
}

func (t *MchMemberCardService) SubmitMemberCardUserInfoEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	//log.Printf("user_enter_session_from_card event:\n%s\n", ctx.MsgPlaintext)
	// TODO以后再考虑

	return nil
}

//卡券商户资格处理函数
func (t *MchMemberCardService) CardMerchantCheckResultEventHandler(weappid string, mixedMsg *core.MixedMsg) {

	return
}

//商户端领卡
func (t *MchMemberCardService) FetchCardByWho(who common.Who, cardId string) (err error) {
	cardIdInt, err := utils.StringToInt64(cardId)
	if err != nil {
		return err
	}

	mchMemberCard := t.tbMchMemberCard.RecodeById(cardIdInt)
	if mchMemberCard == nil {
		return fmt.Errorf("cardid<%d> not found", cardIdInt)
	}

	if mchMemberCard.CardMode != CARD_MODE_MCH { //只有纯商户卡能使用此接口领取，兼容微信卡领取统一走微信推送消息接口
		return fmt.Errorf("not support for card mode <%s>", mchMemberCard.CardMode)
	}

	return nil
}

func (t *MchMemberCardService) CountByWho(who *common.Who)  (int64, error) {
	page := 1
	psize := 1

	_, total, err := t.tbMchMemberCard.ListByWho(who, page, psize) //只是使用Count的功能
	if err != nil {
		return 0, err
	}

	return total, nil
}

func (t *MchMemberCardService)GetWhoByWxCardIdAndUnionId(cardid string, unionId string) (*common.Who, error){

	mchcard := t.tbMchMemberCard.RecodeByWxCardId(cardid)
	if mchcard != nil {
		return nil, fmt.Errorf("not found cardid<%s>", cardid)
	}

	userdb := t.wxUserService.GetUserByUionId(unionId)
	if userdb == nil {
		return nil, fmt.Errorf("not found union id<%s>", unionId)
	}

	who := common.NewWho(mchcard.MiniAppId, mchcard.TenantId, userdb.Id)
	return who, nil
}


func (t *MchMemberCardService) ListMemberCardByWho(who *common.Who, page, psize int) (result []MchMemberCard, total int64, err error) {
	result, total, err = t.tbMchMemberCard.ListByWho(who, page, psize)
	if err != nil {
		return nil, 0, err
	}

	return result, total, nil
}

func (t *MchMemberCardService) GetMemberCardByUserCardId(userCardId int64) *MchMemberCard {
	userCard := t.mchUserMemberCardService.GetMchUserMemberCardById(userCardId)

	memberCard := t.tbMchMemberCard.RecodeById(userCard.MchCardId)
	return memberCard

}


